package com.tuling.controller;

import java.util.ArrayList;
import java.util.List;

import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSON;
import com.tuling.NodeInfo;
import com.tuling.ZookeeperRegister;
@Controller
public class AdminController {
	ZookeeperRegister register = new ZookeeperRegister();

	@RequestMapping("/list")
	public ModelAndView list(ModelAndView  mv) {
		List<NodeInfo> nodeList = new ArrayList<>();
		ZooKeeper zk = register.getConnection(new Watcher() {

			@Override
			public void process(WatchedEvent event) {

			}

		});
		try {
			
			List<String> list = zk.getChildren(ZookeeperRegister.ROOT, true);
			for (String node : list) {
				System.out.println(node);
				byte[] data = zk.getData(ZookeeperRegister.ROOT + "/" + node, true, null);
				NodeInfo nodeInfo = JSON.parseObject(new String(data), NodeInfo.class);
				nodeList.add(nodeInfo);
			}
		} catch (KeeperException | InterruptedException e) {
			e.printStackTrace();
		}
		mv.addObject("nodeList" , nodeList);
		mv.setViewName("admin");
		return mv;
	}
}
